package com.xingkeduo.gateway.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;

import com.xingkeduo.gateway.authority.domain.CommonDomain;
import com.xingkeduo.gateway.authority.pojo.Token;
import com.xingkeduo.util.pojo.exception.AuthorityException;
import com.xingkeduo.util.pojo.exception.SystemException;
import com.xingkeduo.util.tool.ReturnUtil;

import reactor.core.publisher.Mono;

/**
 * token过滤
 * 
 * @author GJ
 * @time 2018年12月4日 下午1:27:11
 * @description
 */
@Component
public class TokenClearCheckGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
	@Autowired
	private CommonDomain commonDomain;

	@Override
	public GatewayFilter apply(Object config) {
		return (exchange, chain) -> {
			ServerHttpRequest request = exchange.getRequest();
			String token = request.getHeaders().getFirst("token");

			// 设置返回
			ReturnUtil returnUtil = new ReturnUtil();
			ServerHttpResponse response = exchange.getResponse();

			// 设置headers
			HttpHeaders httpHeaders = response.getHeaders();
			httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
			httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");

			// 校验token的合法性
			if (token != null) {
				// 合法
				try {
					Token tokenObject = new Token();
					tokenObject.setAccessToken(token);

					commonDomain.clearAuthority(tokenObject);
					return chain.filter(exchange);

				} catch (AuthorityException ae) {
					ae.printStackTrace();
					DataBuffer bodyDataBuffer = response.bufferFactory()
							.wrap(returnUtil.getException(ae.getCode(), ae.getMessage()).getBytes());
					return response.writeWith(Mono.just(bodyDataBuffer));
				} catch (Throwable e) {
					e.printStackTrace();
					DataBuffer bodyDataBuffer = response.bufferFactory().wrap(returnUtil
							.getException(SystemException.Type.DEFAULT.getCode(), SystemException.Type.DEFAULT.getMsg())
							.getBytes());
					return response.writeWith(Mono.just(bodyDataBuffer));
				}
			}

			// 设置body
			DataBuffer bodyDataBuffer = response.bufferFactory().wrap(returnUtil
					.getException(AuthorityException.Type.LOGIN.getCode(), AuthorityException.Type.LOGIN.getMsg())
					.getBytes());
			return response.writeWith(Mono.just(bodyDataBuffer));
		};
	}
}
